import subprocess
from common.initpath import oldexcelsave, newexcelsave, init_excel_dir, server_info_path
import re


def diff_by_version(svn_url: str, old_v: int, new_v: int):
    init_excel_dir()
    files = []
    _v = f'{old_v}:{new_v}'
    cmd_svn = ["svn", '--config-option', 'servers:global:http-chunked-requests=no',
               "diff", "--summarize", '-r', _v, svn_url]
    result_v = exc_cmd(cmd_svn)
    if result_v is '':
        return FileNotFoundError('svn拉取文件为空')
    for re in result_v.splitlines():
        if re.split()[0] is 'M' and len(re.split()[1].split('/')[-1]) < 40:
            files.append(re.split()[1])
    for file in files:
        print(f"正在拉取文件{file}")
        subprocess.Popen(f'svn export -r {old_v} {file} {oldexcelsave}', creationflags=subprocess.CREATE_NO_WINDOW)
        subprocess.Popen(f'svn export -r {new_v} {file} {newexcelsave}', creationflags=subprocess.CREATE_NO_WINDOW)
    return True


def diff_by_url(old_url: str, new_url: str):
    init_excel_dir()
    files = []
    cmd_svn = ["svn", '--config-option', 'servers:global:http-chunked-requests=no',
               "diff", "--summarize", old_url, new_url]
    result_url = exc_cmd(cmd_svn)
    if result_url is '':
        return FileNotFoundError('svn拉取文件为空')
    for re in result_url.splitlines():
        if re.split()[0] is 'M' and len(re.split()[1].split('/')[-1]) < 40:
            files.append(re.split()[1].split('/')[-1])
    for file in files:
        print(f"正在拉取文件{file}")
        print(f'svn export {old_url}/{file} {oldexcelsave}')
        subprocess.Popen(f'svn export {old_url}/{file} {oldexcelsave}', creationflags=subprocess.CREATE_NO_WINDOW)
        subprocess.Popen(f'svn export {new_url}/{file} {newexcelsave}', creationflags=subprocess.CREATE_NO_WINDOW)
    return True


# 获取svn版本号
def get_svn_version(svn_url: str):
    svn_info = exc_cmd(['svn', 'ls', svn_url])  # 20代表取多少个
    return svn_info.split('/\n')[-4:-1][::-1]


# 拉取服务器版本数据
def get_server_info(svn_url: str, version: str):
    cmd = ['svn', 'checkout', svn_url, server_info_path + r'\\' + version]
    re = exc_cmd(cmd)
    if re is not None:
        return True
    else:
        return False


def exc_cmd(cmd: list):
    try:
        re = subprocess.check_output(cmd, creationflags=subprocess.CREATE_NO_WINDOW, text=True, shell=True)
    except Exception as e:
        raise e
    return re


if __name__ == '__main__':
    svnurl = r'http://cd.devsvn.uuzuonline.com/svn/sango_server/ioe_server/release/v2.8.1'
    # cmd = f'svn info {svnurl} --show-item revision'
    # re = exc_cmd(cmd)
    re = get_server_info(svnurl, 'v2.8.1')

    # flag = diff_by_version(svnurl, 95202, 95206)
    # diff_by_url('http://cd.devsvn.uuzuonline.com/svn/sango_server/ioe_server/release/v2.7.7/config/excel',
    #             'http://cd.devsvn.uuzuonline.com/svn/sango_server/ioe_server/release/v2.8.0/config/excel')
